<template>
  <div style="padding-top:85px;">
    <div id="backtest_detail">
      <!--回测名行-->
      <div id="backtestnav" style="display:flex;flex-direction: row;justify-content:space-between;align-items:center;">
        <div
          style="margin-left: 20px;margin-top: 7px;margin-bottom: 7px; display:flex;flex-direction: row"
        >
          <i class="iconfont icon-fanhui" @click="back"></i>
          <div style="font-size:20px;">{{backtestdate.strategyName}}</div>
        </div>
        <!-- <div id="strategynav_right">
          <div style="font-size:18px;margin-right:10px;" class="nav_right" @click="bianjicelue">编辑策略</div>
          <div style="font-size:18px;margin-right:10px;" class="rightnavactive nav_right">回测列表</div>
        </div> -->
      </div>

      <!--模拟交易行-->
      <div id="backtestnav2">
        <div style="display:flex;flex-direction: row;justify-content: flex-start;align-items:center;">
          <span class="left span">设置：</span>
          <div class="span">{{backtestdate.starttime}} 到 {{backtestdate.endtime}}</div>
          <!-- <span class="span">￥10000</span> -->
          <span class="span">|</span>
          <div v-if="runflag === 1" style="display:flex;flex-direction: row;justify-content: flex-start;align-items:center;">
            <i class="iconfont icon-selection" style="color: #58b861;"></i>
            <span style="font-size: 16px;">回测完成</span>
          </div>
          <div v-else style="display:flex;flex-direction: row;justify-content: flex-start;align-items:center;">
            <i class="iconfont icon-dengdai" ></i>
            <span style="font-size: 16px;">回测进行中</span>
          </div>
        </div>
        <div v-if="permission.indexOf('E2') != -1" class="btn" style="margin-right: 20px;display:flex;align-items:center;" @click="newsimu_flag = true">
          <i class="iconfont icon-tubiaozhexiantu"></i>
          <span class="glyphicon glyphicon-equalizer" style="margin-right: 2px;"></span>模拟交易
        </div>
      </div>

      <!--回测详情-->
      <div id="gray_background" style="display:flex;flex-direction: row;justify-content:space-around;">
        <div id="backtest-left" style="width:15%;">
          <ul class="u">
            <li style="margin-top: 20px;" @click="syshow()" :class="{'active':shows==1}">
              <div>
                <i class="iconfont icon-ico_home_obligation" style="margin-right:8px;"></i>收益概览
              </div>
            </li>
            <li @click="jyshow()" :class="{active:shows==2}">
              <div>
                <i class="iconfont icon-jiaoyimingxi" style="margin-right:8px;"></i>交易明细
              </div>
            </li>
            <li @click="lsshow()" :class="{active:shows==3}">
              <div>
                <i class="iconfont icon-lishishuju" style="margin-right:8px;"></i>历史持仓
              </div>
            </li>
          </ul>
        </div>

        <div style="width: 75%;">
          <!--收益概述-->
          <div id="backtest-right" :class="{'content_active':shows!=1}" >
            <div id="backtestrightnav" style="width:100%">
              <span>收益概述</span>
            </div>
            <div id="backtestrightcontent" style="height:680px">
              <table id="backtestresult_table">
                <tr>
                  <td>策略收益</td>
                  <td>实际收益</td>
                  <td>策略年化收益率</td>
                  <!-- <td>基准化收益</td> -->
                </tr>
                <tr v-if="runflag === 1">
                  <td>{{backtestdate.profit}}</td>
                  <td>{{backtestdate.standardprofit}}</td>
                  <td>{{backtestdate.yearprofit | keepTwoNum}}</td>
                </tr>
                <tr v-else>
                  <td>--</td>
                  <td>--</td>
                  <td>--</td>
                  <!-- <td>--</td> -->
                </tr>
              </table>
              <!--图表-->
              <div v-if="runflag === 1">
                <div style="width: 100%;height:600px;" id="backtest_chart"></div>
              </div>
              <div v-else style="width: 100%;height:600px;"  >
                <div style="display:flex;justify-content:center;align-items:center;height:550px">
                  <i class="iconfont icon-dengdai" ></i>
                </div>
              </div>
            </div>
          </div>

          <!--交易明细-->
          <div id="backtest-right" :class="{'content_active':shows!=2}">
            <div id="backtestrightnav">
              <span>交易明细</span>
            </div>
            <div id="backtestrightcontent" style="height:675px;" >
              <table id="transaction_detail_title">
                <tr>
                  <td width="15%">日期</td>
                  <td width="20%">交易编号</td>
                  <td width="10%">股票代码</td>
                  <td width="10%">交易类型</td>
                  <td width="10%">下单类型</td>
                  <td width="10%">交易额</td>
                  <td width="8%">成交数量</td>
                  <td width="7%">手续费</td>
                  <td width="10%">盈亏</td>
                </tr>
              </table>
              <el-scrollbar style="height:calc(100% - 80px )">
              <table id="transaction_detail_table">
                <tr v-for="item in orderList" :key="item.id">
                  <td width="15%">{{item.time}}</td>
                  <td width="20%">{{item.tradenumber}}</td>
                  <td width="10%">{{item.stockNumber}}</td>
                  <td width="10%" v-if="item.ordertype === 1">买</td>
                  <td width="10%" v-if="item.ordertype === 2">卖</td>
                  <td width="10%" v-if="item.type === 1">市价单</td>
                  <td width="10%" v-if="item.type === 2">县价单</td>
                  <td width="10%">{{item.volume}}</td>
                  <td width="8%">{{item.entrusnumber}}</td>
                  <td width="7%">{{item.servicecharge}}</td>
                  <td width="10%">{{item.profit}}</td>
                </tr>
                <tr v-if="runflag === 2"><td  colspan="9"><i class="iconfont icon-dengdai"></i></td></tr>
              </table>
              </el-scrollbar>
              <!--图标-->
              <div id></div>
            </div>
          </div>

          <!--历史持仓-->
          <div id="backtest-right" :class="{'content_active':shows!=3}">
            <div id="backtestrightnav">
              <span>历史持仓</span>
            </div>
            <div id="backtestrightcontent" style="height:600px;">
              <table id="historical_position_title">
                <tr>
                  <!-- <td width="10%">展开/收起</td> -->
                  <td width="35%">日期</td>
                  <td width="25%">股票代码</td>
                  <td width="25%">股票名称</td>
                  <td width="15%">仓位合计</td>
                </tr>
              </table>
              <el-scrollbar style="height:85%">
              <table id="historical_position_table">
                <tr v-for="(item,index) in historyposList" :key="index" id="historical_position_table_lt">
                  <td width="35%">{{item.date}}</td>
                  <td width="25%">{{item.stockNumber}}</td>
                  <td width="25%">{{item.stockName}}</td>
                  <td width="15%">{{item.surplus}}</td>
                </tr>
                <!-- <tr id="historical_position_table_lt" @click="history()">
                  <td width="10%">
                    <i v-show="!historical_flag" class="iconfont icon-xiangshang"></i>
                    <i v-show="historical_flag" class="iconfont icon-xiangxia"></i>
                  </td>
                  <td width="15%">--</td>
                  <td width="15%">--</td>
                  <td width="10%"></td>
                  <td width="10%"></td>
                  <td width="10%"></td>
                  <td width="15%">总资产：--</td>
                  <td width="15%">累计盈亏:--</td>
                </tr> -->
                <!-- <tr id="historical_position_table_lc" v-if="historical_flag">
                  <td width="10%">--</td>
                  <td width="15%">--</td>
                  <td width="15%">--</td>
                  <td width="10%">--</td>
                  <td width="10%">--</td>
                  <td width="10%">--</td>
                  <td width="15%">--</td>
                  <td width="15%">--</td>
                </tr> -->
              </table>
              </el-scrollbar>
              <!--图标-->
              <div id></div>
            </div>
          </div>
        </div>
      </div>
      <div class="mimachangebox">
        <el-dialog title="新建模拟交易" width="600px" :visible.sync="newsimu_flag" style="border-radius: 4px;"  center>
          <div style="display:flex;justify-content:center;flex-direction:column">
          <el-form :model="newtrade">
            <!-- <el-form-item label="交易名称"  label-width="160px">
              <el-input type="text" v-model="newtrade.tradeName" v-validate="'required'" name="name" placeholder="请输入交易名称" clearable></el-input>
              <span class="help is-danger" style="color:red;font-size:15px;">{{ errors.first('name') }}</span>
            </el-form-item> -->
            <el-form-item label="运行周期" label-width="160px">
              <el-select v-model="newtrade.runTimeCycle" placeholder="请选择" v-validate="'required'" name="运行周期">
                  <el-option key="1" label="1分钟" value="1"></el-option>
                  <el-option key="2" label="15分钟" value="2"></el-option>
                  <el-option key="3" label="30分钟" value="3"></el-option>
                  <el-option key="4" label="1小时" value="4"></el-option>
                  <el-option key="5" label="2小时" value="5"></el-option>
                  <el-option key="6" label="1天" value="6"></el-option>
                  <el-option key="7" label="2天" value="7"></el-option>
                  <el-option key="8" label="7天" value="8"></el-option>
              </el-select>
              <div class="help is-danger" style="color:red;font-size:15px;">{{ errors.first('运行周期') }}</div>
            </el-form-item>
            <el-form-item label="股票名称" label-width="160px">
              <!-- <el-input type="text" v-model="newtrade.stock" placeholder="请输入股票代码" v-validate="'required'" name="股票代码"  clearable></el-input>
              <div class="help is-danger" style="color:red;font-size:15px;">{{ errors.first('股票代码') }}</div> -->
              <el-autocomplete
                popper-class="my-autocomplete"
                v-model="newtrade.stock"
                :fetch-suggestions="getStocknumberData"
                placeholder="请输入内容"
                @select="handleSelect">
                <i
                  class="el-icon-edit el-input__icon"
                  slot="suffix"
                  @click="handleIconClick">
                </i>
                <template slot-scope="{ item }">
                  <div class="name">{{item.stocknumber}}{{ item.stockname }}</div>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-form>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" style="background-color:#3C7EEE;width:120px;border:none;" @click="newsimu_flag = false;newSimulatedtrade()">确 定</el-button>
            <el-button @click="newsimu_flag = false;newtrade.tradeName='';newtrade.strategyId='';newtrade.stock='';newtrade.runTimeCycle=''" style="background-color:#cccccc;color:#ffffff;width:120px;">取 消</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<style scoped>
#backtestrightcontent{
  background: #fff;
}
#strategynav_right {
  display: flex;
  flex-direction: row;

}
.rightnavactive {
  color: #255da8;
  border-bottom: 4px solid #255da8;
}
.nav_right:hover{
    color: #337ab7;
}
.u li {
  list-style: none;
}
.iconfont {
  font-size: 25px;
}
#backtestnav2 {
  width: 100%;
  height: 50px;
  border-bottom: solid 1px #d1d3da;
  border-top: solid 1px #d1d3da;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
.span {
  font-size: 16px;
  padding-left: 10px;
}
.left {
  padding-left: 20px;
}
.btn {
  border-radius: 4px;
  height: 40px;
  background-color: red;
  color: #fff;
  cursor: pointer;
}
#gray_background {
  background: #e8ecf0;
  min-height: calc(100vh - 186px);
}
#backtestrightnav {
  margin-top: 20px;
  margin-right: 35px;
  width: 100%;
  background-color: #f7f7f7;
  font-size: 14px;
  font-weight: 700;
  padding: 10px 10px;
}
#backtestresult_table,
#transaction_detail_title,
#historical_position_title {
  text-align: center;
  position: relative;
  left: 0;
  /* top: 10px; */
  width: 100%;
  height: 80px;
  background-color: #ffffff;
}

#transaction_detail_table,
#historical_position_table {
  text-align: center;
  background-color: white;
  width: 100%;
}
#transaction_detail_table tr,
#historical_position_table tr {
  height: 56px;
  border-top: 1px solid #e8ecf0;;
}

/*左导航栏*/
#backtest-left li {
  padding: 10px 30px;
  /* margin-left: 20px; */
  width: 100%;
}
.active {
  background-color: #255da8;
}

.content_active {
  display: none;
}

.historyflag {
  display: none;
}
.mimachangebox >>> .el-input__inner {
  width: 270px;
}
</style>
<style>
.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;
    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }
  }
}
</style>
<script>
import {messages} from '../../validate/reg'
import moment from "moment"
export default {
  data() {
    return {
      strategy_name: "小市值股票交易策略",
      shows: 1,
      historical_flag: false,
      backtestId:'',
      sessionToken:'',
      // 运行是否结束
      runflag:'',
      // 订单列表
      orderList:'',
      interval:'',
      historyposList:'',
      drawdata:'',
      drawvalue:[],
      drawdate:[],
      backtestdate:'',
      newtrade:{
        tradeName:'',
        strategyId:'',
        runTimeCycle:'',
        stock:''
      },
      newsimu_flag:false,
      permission:[],
    };
  },
  filters:{
    keepTwoNum:function(value){
      value = Number(value)
      return value.toFixed(2)
    }
  },
  mounted(){
    if(localStorage.getItem('permission') != null){
      this.permission = localStorage.getItem('permission').split(",")
    }
    this.SessionToken = localStorage.getItem('SessionToken')
    this.backtestId = localStorage.getItem('backtestId')
    // this.backtestId = 270
    console.log(this.permission)
    if(this.backtestId !== ''){
      this.interval = setInterval(this.getOrderList,2000)
    }
  },
  methods: {
    // 获取股票代码下拉
    getStocknumberData(queryString, cb){
      this.$http.get('stock/listByStockNameOrStockNumber?keyword='+this.newtrade.stock+'').then((resp) => {
        if (resp.data.status === 200) {
          // console.log(resp.data)
          this.stocknumberList = resp.data.data
          cb(this.stocknumberList)
        } else {
          this.$message(resp.data.msg)
        }
      })
      
    },
    handleSelect(item) {
      // console.log(item);
      this.newtrade.stock = item.stocknumber
    },
    handleIconClick(ev) {
      // console.log(ev);
    },

    getOrderList(){
      console.log('定时器运行')
      this.$http.get('inquireIsRunOver?recordId='+this.backtestId+'').then((resp) => {
        if (resp.data.status === 200) {
          // console.log(resp)
          this.runflag = resp.data.data
          if(this.runflag === 2){
              // 获取订单
            this.$http.get('getOrderPageByRecordId?recordId='+this.backtestId+'&pageIndex=1&pageSize=999').then((resp) => {
              if (resp.data.status === 200) {
                this.orderList=resp.data.data.list
              } else {
                // console.log(resp)
                this.$message.error(resp.data.message)
              }
            })
            // 获取历史持仓
            this.$http.get('getTradingPositionMsg?recordId='+this.backtestId+'').then((resp) => {
              if (resp.data.status === 200) {
                this.historyposList=resp.data.data
                // console.log(this.historyposList)
              } else {
                // console.log(resp)
                this.$message.error(resp.data.message)
              }
            })
            //获取收益图表数据
            this.$http.get('getTradingAccountMsg?recordId='+this.backtestId+'').then((resp) => {
              if (resp.data.status === 200) {
                this.drawdata=resp.data.data.profitList
                // console.log(this.drawdata)
              } else {
                this.$message.error(resp.data.message)
              }
            })
          }
            // this.$message.success(resp.data.message)
         } else {
          this.$message.error(resp.data.message)
        }
      })
      if(this.runflag === 1){
        console.log('定时器结束')
        this.$http.get('getOrderPageByRecordId?recordId='+this.backtestId+'&pageIndex=1&pageSize=999').then((resp) => {
          if (resp.data.status === 200) {
            // this.$message.success(resp.data.message)
            this.orderList=resp.data.data.list
            clearInterval(this.interval)
          } else {
            this.$message.error(resp.data.message)
          }
        })
        // 获取历史持仓
        this.$http.get('getTradingPositionMsg?recordId='+this.backtestId+'').then((resp) => {
          if (resp.data.status === 200) {
            this.historyposList=resp.data.data
          } else {
            this.$message.error(resp.data.message)
          }
        })
        //获取收益图表数据
        this.$http.get('getTradingAccountMsg?recordId='+this.backtestId+'').then((resp) => {
          if (resp.data.status === 200) {
            this.drawdata=resp.data.data.profitList
            let a = 0
            for(let i=0;i<this.drawdata.length;i++){
              a=this.drawdata[i].profit+a
              this.drawvalue.push(a)
              this.drawdate.push(this.drawdata[i].date)
            }
            let day = resp.data.data.day
            // 获取回测结果数据
            this.$http.get('inquireTestRecordMsg?recordId='+this.backtestId+'').then((resp) => {
              if (resp.data.status === 200) {
                this.backtestdate=resp.data.data
                this.backtestdate.yearprofit = 250*Number(this.backtestdate.profit)/day 
                // this.backtestdate.starttime = moment(new Date(parseInt(this.backtestdate.starttime))).format("YYYY-MM-DD")
                // this.backtestdate.endtime = moment(new Date(parseInt(this.backtestdate.endtime))).format("YYYY-MM-DD")
                // console.log(this.backtestdate.starttime,this.backtestdate.endtime)
              } else {
                this.$message.error(resp.data.message)
              }
            })
            this.drawbacktestcharts()
          } else {
            this.$message.error(resp.data.message)
          }
        })
        
      }
    },
    active(num) {
      this.shows = num;
    },
    content_active(num) {
      this.shows = num;
    },
    historyflag(a) {
      this.historical_flag = a;
    },
    syshow() {
      this.shows = 1
    },
    jyshow() {
      this.shows = 2
    },
    lsshow() {
      this.shows = 3
    },
    history() {
      this.historical_flag = !this.historical_flag;
    },
    bianjicelue() {
      this.$router.push('/strategy_create')
    },
    back(){
      this.$router.go(-1);
    },
    drawbacktestcharts () {
      this.charts = this.$echarts.init(document.getElementById('backtest_chart'));
      this.charts.setOption( {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          // data: ['邮件营销', '联盟广告', '视频广告', '直接访问', '搜索引擎']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.drawdate
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
                        // name: '邮件营销',
            type: 'line',
            stack: '总量',
            data: this.drawvalue
          }
        ]

      });
    },
    newSimulatedtrade(){
      // runInvestment?strategyId=57&runTimeCycle=1&stock=000001&sessionToken=ca5c3a8426d30d56b47743f8205e3393
      let strategyId = localStorage.getItem('strategyId')
      this.$http.post('runInvestment?sessionToken='+this.SessionToken+'&strategyId='+strategyId+'&runTimeCycle='+this.newtrade.runTimeCycle+'&stock=000001').then((resp) => {
          if (resp.data.status === 200) {
            localStorage.setItem('inrecordId',resp.data.data)
            this.$message.success('新建模拟交易成功！')
            this.$router.push('/gaishu')
          } else {
            this.$message.error(resp.data.msg)
          }
      })
    }
  }
};
</script>